// packageFT/seek-guide/seek-guide.js
const app = getApp()
import { formatDate } from '../../utils/util'
import WxValidate from '../../utils/WxValidate'
const attractionsList = [
  { id: 1, text: '都江堰' },
  { id: 2, text: '大熊猫基地' },
  { id: 3, text: '九寨沟' },
  { id: 4, text: '黄龙风景区' }
]
const guideLevelColumns = [
  { id: 1, text: '普通（180/天）', price: 180 },
  { id: 2, text: '优质（300/天）', price: 300 }
]
const guideList = [
  {id: 1, name: '张三', level: '普通导游', years: 2, phone: '13222222222', introduction: '本人性格开朗，爱好广泛，在学习期间积极参加各种活动，多次组织一些校园活动。积极向上且对待工作认证负责，有上进心', thumb: '/image/level-icon.png'},
  {id: 2, name: '李四', level: '优质导游', years: 3, phone: '13222222222', introduction: '本人性格开朗，爱好广泛，在学习期间积极参加各种活动，多次组织一些校园活动。积极向上且对待工作认证负责，有上进心', thumb: '/image/level-icon.png'},
  {id: 3, name: '王五', level: '普通导游', years: 1, phone: '13222222222', introduction: '本人性格开朗，爱好广泛，在学习期间积极参加各种活动，多次组织一些校园活动。积极向上且对待工作认证负责，有上进心', thumb: '/image/level-icon.png'},
  {id: 4, name: '赵六', level: '优质导游', years: 5, phone: '13222222222', introduction: '本人性格开朗，爱好广泛，在学习期间积极参加各种活动，多次组织一些校园活动。积极向上且对待工作认证负责，有上进心', thumb: '/image/level-icon.png'}
]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      travelCityValue: '',
      chooseTravelCityValue: '',
      travelTimeValue: '',
      travelDays: 0,
      travelTimeStart: '',
      travelTimeEnd: '',
      travelPopulationValue: 1,
      attractionsText: [],
      attractionsIds: [],
      travelCarValue: '',
      guideLevelValue: '',
      appointGuideValue: '',
      appointGuideID: 0,
      remarkValue: '',
      know: 0
    },
    chooseTravelCityShow: false,
    travelCityOptions: [],
    travelTimeShow: false,
    attractionsList,
    chooseTravelCarShow: false,
    travelCarColumns: ['五座车', '七座车', '自备车'],
    chooseGuideLevelShow: false,
    guideLevelColumns,
    guideLevelPrice: 0,
    appointGuideShow: false,
    guideList
  },

  /**
   * 显示/隐藏弹窗
   * @param {Object} e 
   */
  popupToggle: function(e) {
    console.log(e)
    const { text, show } = e.currentTarget.dataset
    this.setData({
      [text]: show
    })
  },

  /**
   * 出行城市选择结束
   * @param {Object} e 
   */
  chooseTravelCityFinish: function(e) {
    const { selectedOptions, value } = e.detail;
    const fieldValue = selectedOptions[1].text
    this.setData({
      'formData.travelCityValue': fieldValue,
      'formData.chooseTravelCityValue': value,
      chooseTravelCityShow: false
    })
  },

  /**
   * 出行时间选择确认
   * @param {Object} e 
   */
  travelTimeConfirm: function(e) {
    const start = e.detail[0]
    const end = e.detail[1]
    const startStr = formatDate(start)
    const endStr = formatDate(end)
    const day = (end - start)/1000/60/60/24 + 1
    const travelTimeValue = `${startStr}~${endStr}(${day}天)`
    this.setData({
      'formData.travelDays': day,
      'formData.travelTimeValue': travelTimeValue,
      'formData.travelTimeStart': startStr,
      'formData.travelTimeEnd': endStr,
      travelTimeShow: false
    })
  },

  /**
   * 数据双向绑定
   * @param {Object} e 
   */
  updateFormData: function(e) {
    const { formdatakey } = e.currentTarget.dataset
    const value = e.detail
    const key = 'formData.' + [formdatakey]
    this.setData({
      [key]: value 
    })
  },

  /**
   * 景点点击
   * @param {Object} e 
   */
  attractionsClick: function(e) {
    const { id, text } = e.currentTarget.dataset.item
    let ids = this.data.formData.attractionsIds
    let texts = this.data.formData.attractionsText
    const idIndex = ids.findIndex(item => item == id)
    const textIndex = texts.findIndex(item => item == text)
    // 存在id
    if (idIndex > -1) {
      ids.splice(idIndex, 1)
    } else {
      ids.push(id)
    }
    // 存在文字
    if (textIndex > -1) {
      texts.splice(textIndex, 1)
    } else {
      texts.push(text)
    }
    this.setData({
      'formData.attractionsIds': ids,
      'formData.attractionsText': texts
    })
  },

  /**
   * 出行工具选择确认
   * @param {Object}} e 
   */
  travelCarConfirm: function(e) {
    const { value } = e.detail
    this.setData({
      'formData.travelCarValue': value,
      chooseTravelCarShow: false
    })
  },

  /**
   * 导游级别选择确认
   * @param {Object}} e 
   */
  guideLevelConfirm: function(e) {
    const { text, price } = e.detail.value
    this.setData({
      'formData.guideLevelValue': text,
      guideLevelPrice: price,
      chooseGuideLevelShow: false
    })
  },

  /**
   * 导游选择确认
   */
  guideConfirm: function() {
    const component = this.selectComponent("#guide-list")
    const { guideID, guideName }= component.data
    if (!guideID) {
      app.tips('请选择导游')
      return
    }
    this.setData({
      'formData.appointGuideID': guideID,
      'formData.appointGuideValue': guideName,
      appointGuideShow: false
    })
  },

  /**
   * 选中知晓
   * @param {Object} e 
   */
  knowChange: function(e) {
    this.setData({
      'formData.know': this.data.formData.know ? 0 : e.detail
    })
  },

  /**
   * 取消寻找导游
   */
  goBack: function() {
    wx.navigateBack({delta: -1})
  },

  /**
   * 发布需求
   */
  submitForm: function() {
    if (!this.WxValidate.checkForm(this.data.formData)) {
      const error = this.WxValidate.errorList[0]
      app.tips(error.msg)
      return
    }
    console.log(this.data.formData)
    app.tips('发布需求，待完善...')
  },

  /**
   * 获取省市列表(出行城市)
   */
  getAddress: function() {
    wx.showLoading({
      title: '加载中...',
    })
    const _this = this
    let urlStr = app.getNetAddresss("member.member-address.address");
    app._postNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const province = resData.data.province.map(item => {
            const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
              return {
                text: item1.areaname,
                value: item1.id + ''
              }
            })
            return {
              text: item.areaname,
              value: item.id + '',
              children: child
            }
          })
          _this.setData({ travelCityOptions: province})
        } else {
          app.tips(resData.msg)
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 表单验证
   */
  initValidate: function() {
    const rules = {
      travelCityValue: {
        required: true
      },
      travelTimeValue: {
        required: true
      },
      attractionsIds: {
        isEmptyArray: true
      },
      travelCarValue: {
        required: true
      },
      guideLevelValue: {
        required: true
      },
      know: {
        min: 1
      }
    }
    const message = {
      travelCityValue: {
        required: '请选择出行城市'
      },
      travelTimeValue: {
        required: '请选择出行时间'
      },
      attractionsIds: {
        isEmptyArray: '请选择景点'
      },
      travelCarValue: {
        required: '请选择出行工具'
      },
      guideLevelValue: {
        required: '请选择导游级别'
      },
      know: {
        min: '必须勾选我已知晓才能提交需求'
      }
    }
    this.WxValidate = new WxValidate(rules, message)
    this.WxValidate.addMethod('isEmptyArray', (value, param) => {
      return value.length > 0
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getAddress()
    this.initValidate()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})